<template>
  <div class="register-container">
    <div class="register-box">
      <div class="register-header">
        <el-page-header title="返回" @back="router.back()"></el-page-header>
        <el-steps style="max-width: 800px" :active="activeStep+1" align-center>
          <el-step title="填写基本信息" :icon="Edit" />
          <el-step title="上传工商资料" :icon="Upload" />
          <el-step title="配置店铺详情" :icon="Picture" />
        </el-steps>
      </div>
      <div class="register-content">
        <el-form
            v-if="activeStep === 0"
            :model="registerForm"
            :rules="registerRules"
            ref="step1FormRef"
            label-width="auto"
            class="register-form"
        >
          <h2>平台注册/入驻</h2>
          <el-form-item label="用户名" prop="username">
            <el-input v-model="registerForm.username" placeholder="请输入用户名" />
          </el-form-item>
          <el-form-item label="密&nbsp;&nbsp;&nbsp; 码" prop="password">
            <el-input v-model="registerForm.password" type="password" placeholder="请输入密码" />
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input v-model="registerForm.confirmPassword" type="password" placeholder="请输入确认密码" />
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="registerForm.phone" placeholder="请输入手机号" />
          </el-form-item>
          <el-form-item label="验证码" prop="captcha">
            <el-input v-model="registerForm.captcha" placeholder="请输入验证码">
              <template #append>
                <el-button ref="sendRef" :style="sendBtnStyle" @click="sendCaptcha()">
                  {{ isSendCaptcha }}
                </el-button>
              </template>
            </el-input>
          </el-form-item>
<!--          <el-form-item label="邮&nbsp;&nbsp;&nbsp; 箱" prop="email">-->
<!--            <el-input v-model="registerForm.email" placeholder="请输入邮箱 / 非必填" />-->
<!--          </el-form-item>-->
          <el-form-item>
            <el-button type="primary" size="large" @click="validateStep1(step1FormRef)" class="register-button">下一步</el-button>
          </el-form-item>
        </el-form>

        <el-form v-if="activeStep === 1" label-width="auto" :model="registerForm" ref="step2FormRef" class="register-form">
          <h2>上传工商资料</h2>
          <!-- 你的工商资料表单内容 -->
          <el-form-item label="负责人" prop="merchantBoss">
            <el-input v-model="registerForm.merchantBoss" placeholder="请输入负责人" />
          </el-form-item>
          <el-form-item label="营业执照" prop="businessLicense">
            <el-upload class="avatar-uploader" :action="uploadParams.uploadUrl" :before-upload="beforeUpload" list-type="picture-card"
                       :on-success="handleUploadSuccess" :show-file-list="false">
              <img v-if="registerForm.businessLicense" :src="getImgUrl(registerForm.businessLicense)" class="avatar"  alt=""/>
              <el-icon v-else class="avatar-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="large" @click="validateStep2(step2FormRef)" class="register-button">下一步</el-button>
            <el-button type="danger" size="large" @click="prevStep" class="register-button">上一步</el-button>
          </el-form-item>
        </el-form>

        <el-form v-if="activeStep === 2" label-width="auto" :model="registerForm" ref="step3FormRef" class="register-form">
          <h2>配置店铺详情</h2>
          <el-form-item label="店铺名称" prop="shopName">
            <el-input v-model="registerForm.shopName" placeholder="请输入店铺名称" />
          </el-form-item>
          <el-form-item label="店铺地址" prop="shopAddress">
            <el-input v-model="registerForm.shopAddress" placeholder="请输入店铺地址" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="large" @click="submitRegister(step3FormRef)" class="register-button">提交</el-button>
            <el-button type="danger" size="large" @click="prevStep" class="register-button">上一步</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="register-tip">
        <el-text class="tip" type="info">
          <b>温馨提示：</b><br />
          1. <b style="color: red">* </b>标记的为必填信息。<br />
          2. 请确保所提供的所有信息真实有效，以免影响您的正常使用。<br />
          3. 如果在注册过程中遇到任何问题，可以随时联系我们客服，我们将竭诚为您服务。
        </el-text>
      </div>
    </div>
    <!--联系客服-->
    <div class="register-contact">
      <el-space wrap>
        <el-card v-for="i in 3" :key="i" class="contact-card">
          <img style="width: 100%;height: auto;object-fit: contain" src="../assets/llk.png" alt="小明的店铺" />
          <template #header>
            <div class="card-header">
              <span>{{ contactName }}</span>
            </div>
          </template>
        </el-card>
      </el-space>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, computed } from 'vue';
import { ElMessage, FormInstance, FormRules } from 'element-plus';
import router from '../router';
import {register} from '@/api/user';
import {Edit, Picture, Plus, Upload} from '@element-plus/icons-vue';
import {getImgUrl} from "@/utils/common.ts";

const step1FormRef = ref<FormInstance>();
const step2FormRef = ref<FormInstance>();
const step3FormRef = ref<FormInstance>();

const registerForm = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  phone: '',
  captcha: '',
  email: '',
  merchantBoss: '',
  businessLicense: '',
  shopName: '',
  shopAddress: '',
});

const activeStep = ref(0);
const contactName = ref('客服微信');

const checkUsername = (_rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入用户名!'));
  }
  callback();
};

const checkPhone = (_rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入手机号!'));
  } else if (!/^[1][3456789][0-9]{9}$/.test(value)) {
    callback(new Error('请输入正确的手机号码格式!'));
  } else {
    callback();
  }
};

const checkEmail = (_rule: any, value: any, callback: any) => {
  if (value !== '') {
    if (!/^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/.test(value)) {
      callback(new Error('请输入正确的邮箱格式!'));
    } else {
      callback();
    }
  }
};

const checkPassword = (_rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入密码!'));
  }
  callback();
};

const checkConfirmPassword = (_rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请再次输入密码'));
  } else if (value !== registerForm.password) {
    callback(new Error('两次输入不一致!'));
  } else {
    callback();
  }
};

const checkMerchantBoss = (_rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入负责人!'));
  }
  callback();
};

const checkRegCaptcha = (_rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入验证码!'));
  }
  callback();
};

const registerRules = reactive<FormRules<typeof registerForm>>({
  username: [{ validator: checkUsername, trigger: 'blur', required: true }],
  password: [{ validator: checkPassword, trigger: 'blur', required: true }],
  confirmPassword: [{ validator: checkConfirmPassword, trigger: 'blur', required: true }],
  phone: [{ validator: checkPhone, trigger: 'blur', required: true }],
  captcha: [{ validator: checkRegCaptcha, trigger: 'blur', required: true }],
  email: [{ validator: checkEmail, trigger: 'blur' }],
  merchantBoss: [{ validator: checkMerchantBoss, trigger: 'blur', required: true }],
  businessLicense: [{ required: true, message: '请上传营业执照', trigger: 'change' }],
  shopName: [{ required: true, message: '请输入店铺名称', trigger: 'blur' }],
  shopAddress: [{ required: true, message: '请输入店铺地址', trigger: 'blur' }],
});

// 验证码区域文字说明
const sendRef = ref()
const isSendCaptcha = ref<string>('发送验证码')

const sendBtnStyle = computed(() => {
  return {
    color: 'white',
    backgroundColor: isSendCaptcha.value === '发送验证码' ? '#42d392' : 'gray'
  };
});

const sendCaptcha = () => {
  if (!isSendCaptcha.value.endsWith('发送验证码')) return;

  step1FormRef.value?.validateField('phone', (errorMessage) => {
    if (errorMessage) { // 如果验证通过（即 errorMessage 为空）
      isSendCaptcha.value = '60秒后重新发送';
      let countDown = 60;
      const timer = setInterval(() => {
        countDown--;
        isSendCaptcha.value = `${countDown}秒后重新发送`;
        if (countDown <= 0) {
          clearInterval(timer);
          isSendCaptcha.value = '重新发送验证码';
        }
      }, 1000);
    } else {
      ElMessage.error('请输入正确的手机号码格式!');
    }
  });
};

const nextStep = () => {
  activeStep.value++;
};

const prevStep = () => {
  activeStep.value--;
};
const validateStep1 = async (formEl: FormInstance | undefined) => {
  console.log('表单校验：', formEl);
  if (!formEl) return;
  try {
    const valid = await formEl.validate();
    // console.log('表单校验：', valid);
    nextStep();
  } catch (fields) {
    console.log('表单校验：', false, fields);
    ElMessage.error('请完成当前步骤的所有必填信息');
  }
};

const validateStep2 = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
    try {
      const valid = await formEl.validate();
      console.log('表单校验：', valid);
      nextStep();
    } catch (fields) {
      console.log('表单校验：', false, fields);
      ElMessage.error('请完成当前步骤的所有必填信息');
    }
};

const submitRegister = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
    const valid = await formEl.validate();
    if (valid) {
      console.log("注册信息：", registerForm)
      const res = await register(registerForm);
      if (res.code === 200) {
        ElMessage.success('注册成功');
        setTimeout(() => {
          router.push('/login');
        }, 1000);
      } else {
        ElMessage.error(res.data.message);
      }
    } else {
      ElMessage.error('请完成当前步骤的所有必填信息');
    }
};

// 上传图片
const uploadParams = {
  uploadUrl: "http://localhost:8018/file/uploadAvatar",
};

const handleUploadSuccess = (res: any) => {
  if (res.code == 200) {
    ElMessage.success("上传成功");
    registerForm.businessLicense = res.data.url;
  } else {
    ElMessage.error(res.describe);
  }
};

const beforeUpload = (file: any) => {
  const isJPG = file.type === 'image/jpeg';
  const isPNG = file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG && !isPNG) {
    ElMessage.error('上传图片只能是 JPG 或 PNG 格式!');
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!');
  }
  return (isJPG || isPNG) && isLt2M;
};
</script>

<style scoped>
.register-container {
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中，如果需要的话 */
  height: 100vh; /* 如果需要垂直居中，设置容器高度为视口高度 */
  background-color: #f0f2f5;
}

.register-box {
  max-width: 800px;
  width: 100%; /* 确保宽度适应内容或最大宽度 */
  height: 100%; /* 确保高度适应内容 */
  background-color: white;
}

.register-content {
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中，如果需要的话 */
  width: 100%;
  margin-top: 20px;
}

.register-form {
  width: 68%;
}

.register-form h2 {
  text-align: center;
  margin-bottom: 20px;
  color: #42d392;
}

.register-button {
  width: 100%;
  margin: 10px;
  background-color: #42d392;
  border: none;
  border-radius: 4px;
  color: white;
  font-size: 18px;
  cursor: pointer;
}

.register-button:hover {
  background-color: #94b3e2;
}

.register-tip {
  margin-top: 30px;
  display: flex;
  justify-content: center;
}

.tip {
  text-align: left;
}

.register-contact {
  width: 10%;
  height: 100vh;
  margin-top: 30px;
  margin-left: 30px;
  display: flex;
  align-items: center;
}

.contact-card {
  width: 178px;
}

.avatar-uploader {
  text-align: center;
  margin: 30px 0;

  .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 50%;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
    margin: 0 auto;
  }

  .avatar {
    width: 150px;
    height: 150px;
    object-fit: cover;
  }
}
</style>